<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="关联商品SKU ID" prop="productSkuId">
        <el-input
          v-model="queryParams.productSkuId"
          placeholder="请输入关联商品SKU ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请参与价格" prop="applicationParticipationPrice">
        <el-input
          v-model="queryParams.applicationParticipationPrice"
          placeholder="请输入申请参与价格"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请状态" prop="applicationStatus">
        <el-select v-model="queryParams.applicationStatus" placeholder="请选择申请状态" clearable style="width: 180px">
          <el-option label="未提交" :value="0" />
          <el-option label="待审核" :value="1" />
          <el-option label="审核通过" :value="2" />
          <el-option label="审核驳回" :value="3" />
          <el-option label="已上架" :value="4" />
          <el-option label="已下架" :value="5" />
        </el-select>
      </el-form-item>
      <el-form-item label="申请时间" prop="applicationTime">
        <el-date-picker clearable
          v-model="queryParams.applicationTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择申请时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['group:application_active:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['group:application_active:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['group:application_active:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['group:application_active:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="application_activeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="申请ID" align="center" prop="id" />
      <el-table-column label="关联平台拼团活动" align="center" prop="platformGroupActivityId">
        <template slot-scope="scope">
          <span>{{ getPlatformGroupActivityName(scope.row.platformGroupActivityId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="关联商家" align="center" prop="merchantId">
        <template slot-scope="scope">
          <span>{{ getMerchantName(scope.row.merchantId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="关联商品SKU" align="center" prop="productSkuId">
        <template slot-scope="scope">
          <span>{{ getProductSkuName(scope.row.productSkuId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请参与价格" align="center" prop="applicationParticipationPrice" />
      <el-table-column label="申请状态" align="center" prop="applicationStatus">
        <template slot-scope="scope">
          <el-tag :type="getApplicationStatusType(scope.row.applicationStatus)">
            {{ getApplicationStatusText(scope.row.applicationStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="申请时间" align="center" prop="applicationTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.applicationTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <!-- 商家可操作按钮 -->
          <el-button
            v-if="scope.row.applicationStatus === 0"
            size="mini"
            type="text"
            icon="el-icon-upload"
            @click="handleSubmitApplication(scope.row)"
            style="color: #409EFF;"
          >提交申请</el-button>
          
          <el-button
            v-if="scope.row.applicationStatus === 2"
            size="mini"
            type="text"
            icon="el-icon-top"
            @click="handleActivateApplication(scope.row)"
            style="color: #67C23A;"
          >上架</el-button>
          
          <el-button
            v-if="scope.row.applicationStatus === 2"
            size="mini"
            type="text"
            icon="el-icon-bottom"
            @click="handleDeactivateApplication(scope.row)"
            style="color: #E6A23C;"
          >下架</el-button>
          
          <!-- 管理员可操作按钮 -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['group:application_active:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['group:application_active:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :layout="'total, sizes, prev, pager, next, jumper'"
      @pagination="getList"
    />

    <!-- 添加或修改商家拼团申请对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="关联平台拼团活动" prop="platformGroupActivityId">
          <el-select v-model="form.platformGroupActivityId" placeholder="请选择平台拼团活动" clearable style="width: 100%" @change="onPlatformActivityChange">
            <el-option
              v-for="item in platformGroupActivityOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联商家" prop="merchantId">
          <el-select v-model="form.merchantId" placeholder="请选择商家" clearable style="width: 100%">
            <el-option
              v-for="item in merchantOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联商品SKU" prop="productSkuId">
          <el-select v-model="form.productSkuId" placeholder="请选择商品SKU" clearable style="width: 100%">
            <el-option
              v-for="item in productSkuOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="申请参与价格" prop="applicationParticipationPrice">
          <el-input v-model="form.applicationParticipationPrice" placeholder="请输入申请参与价格" />
        </el-form-item>
        <el-form-item label="申请时间" prop="applicationTime">
          <el-date-picker clearable
            v-model="form.applicationTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择申请时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listApplication_active, getApplication_active, delApplication_active, addApplication_active, updateApplication_active, getPlatformGroupActivities, getMerchants, getMerchantsByActivity, getProductSkus, updateApplicationStatus } from "@/api/group/application_active"

export default {
  name: "Application_active",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 平台拼团活动选项
      platformGroupActivityOptions: [],
      // 商家选项
      merchantOptions: [],
      // 商品SKU选项
      productSkuOptions: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商家拼团申请表格数据
      application_activeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        platformGroupActivityId: null,
        merchantId: null,
        productSkuId: null,
        applicationParticipationPrice: null,
        applicationStatus: null,
        applicationTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        platformGroupActivityId: [
          { required: true, message: "关联平台拼团活动ID不能为空", trigger: "change" }
        ],
        merchantId: [
          { required: true, message: "关联商家ID不能为空", trigger: "change" }
        ],
        productSkuId: [
          { required: true, message: "关联商品SKU ID不能为空", trigger: "blur" }
        ],
        applicationParticipationPrice: [
          { required: true, message: "申请参与价格不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getPlatformGroupActivities()
    // 不再默认加载商家列表，等待用户选择平台活动后动态加载
    this.getProductSkus()
  },
  methods: {
    /** 查询商家拼团申请列表 */
    getList() {
      this.loading = true
      listApplication_active(this.queryParams).then(response => {
        this.application_activeList = response.data.rows
        this.total = response.data.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        platformGroupActivityId: null,
        merchantId: null,
        productSkuId: null,
        applicationParticipationPrice: null,
        applicationStatus: null,
        applicationTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.queryParams.pageNum = 1
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加商家拼团申请"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getApplication_active(id).then(response => {
        this.form = response.data
        
        // 如果已选择了平台活动，加载对应的商家列表
        if (this.form.platformGroupActivityId) {
          this.getMerchantsByActivity(this.form.platformGroupActivityId)
        }
        
        this.open = true
        this.title = "修改商家拼团申请"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 确保数字字段的数据类型正确
          const formData = {
            ...this.form,
            platformGroupActivityId: this.form.platformGroupActivityId ? Number(this.form.platformGroupActivityId) : null,
            merchantId: this.form.merchantId ? Number(this.form.merchantId) : null,
            productSkuId: this.form.productSkuId ? Number(this.form.productSkuId) : null
          }
          
          // 新增时不发送申请状态，由后端设置默认值
          if (this.form.id == null) {
            // 新增时删除申请状态字段
            delete formData.applicationStatus
            
            addApplication_active(formData).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          } else {
            // 修改时保留状态字段
            formData.applicationStatus = this.form.applicationStatus !== null ? Number(this.form.applicationStatus) : null
            
            updateApplication_active(formData).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除商家拼团申请编号为"' + ids + '"的数据项？').then(function() {
        return delApplication_active(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('group/application_active/export', {
        ...this.queryParams
      }, `application_active_${new Date().getTime()}.xlsx`)
    },
    /** 获取平台拼团活动列表 */
    getPlatformGroupActivities() {
      getPlatformGroupActivities().then(response => {
        if (response.code === 200) {
          this.platformGroupActivityOptions = response.data || []
        } else {
          this.platformGroupActivityOptions = []
          this.$modal.msgError(response.msg || '获取平台拼团活动列表失败')
        }
      }).catch(() => {
        this.platformGroupActivityOptions = []
        this.$modal.msgError('获取平台拼团活动列表失败')
      })
    },
    /** 获取商家列表 */
    getMerchants() {
      getMerchants().then(response => {
        if (response.code === 200) {
          this.merchantOptions = response.data || []
        } else {
          this.merchantOptions = []
          this.$modal.msgError(response.msg || '获取商家列表失败')
        }
      }).catch(() => {
        this.merchantOptions = []
        this.$modal.msgError('获取商家列表失败')
      })
    },
    /** 根据平台活动ID获取关联商家列表 */
    getMerchantsByActivity(activityId) {
      if (!activityId) {
        this.merchantOptions = []
        return
      }
      
      getMerchantsByActivity(activityId).then(response => {
        if (response.code === 200) {
          this.merchantOptions = response.data || []
        } else {
          this.merchantOptions = []
          this.$modal.msgError(response.msg || '获取关联商家列表失败')
        }
      }).catch(() => {
        this.merchantOptions = []
        this.$modal.msgError('获取关联商家列表失败')
      })
    },
    /** 平台活动选择变化事件 */
    onPlatformActivityChange(activityId) {
      // 清空商家选择
      this.form.merchantId = null
      
      // 根据选择的活动加载关联商家
      if (activityId) {
        this.getMerchantsByActivity(activityId)
      } else {
        this.merchantOptions = []
      }
    },
    /** 获取商品SKU列表 */
    getProductSkus() {
      getProductSkus().then(response => {
        if (response.code === 200) {
          this.productSkuOptions = response.data || []
        } else {
          this.productSkuOptions = []
          this.$modal.msgError(response.msg || '获取商品SKU列表失败')
        }
      }).catch(() => {
        this.productSkuOptions = []
        this.$modal.msgError('获取商品SKU列表失败')
      })
    },
    /** 根据平台拼团活动ID获取名称 */
    getPlatformGroupActivityName(activityId) {
      if (!activityId || !this.platformGroupActivityOptions.length) {
        return '-'
      }
      const option = this.platformGroupActivityOptions.find(item => item.value === activityId)
      return option ? option.label : activityId
    },
    /** 根据商家ID获取名称 */
    getMerchantName(merchantId) {
      if (!merchantId || !this.merchantOptions.length) {
        return '-'
      }
      const option = this.merchantOptions.find(item => item.value === merchantId)
      return option ? option.label : merchantId
    },
    /** 根据商品SKU ID获取名称 */
    getProductSkuName(skuId) {
      if (!skuId || !this.productSkuOptions.length) {
        return '-'
      }
      const option = this.productSkuOptions.find(item => item.value === skuId)
      return option ? option.label : skuId
    },
    /** 获取申请状态文本 */
    getApplicationStatusText(status) {
      const statusMap = {
        0: '未提交',
        1: '待审核',
        2: '审核通过',
        3: '审核驳回',
        4: '已上架',
        5: '已下架'
      }
      return statusMap[status] || '未知'
    },
    /** 获取申请状态颜色 */
    getApplicationStatusType(status) {
      const typeMap = {
        0: 'info',      // 未提交 - 灰色
        1: 'warning',   // 待审核 - 黄色
        2: 'success',   // 审核通过 - 绿色
        3: 'danger',    // 审核驳回 - 红色
        4: '',          // 已上架 - 蓝色
        5: 'info'       // 已下架 - 灰色
      }
      return typeMap[status] || 'info'
    },
    /** 提交申请 */
    handleSubmitApplication(row) {
      this.$modal.confirm('是否确认提交编号为"' + row.id + '"的申请？').then(() => {
        return this.updateApplicationStatus(row.id, 1) // 状态改为待审核
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('提交成功')
      }).catch(() => {})
    },
    /** 上架申请 */
    handleActivateApplication(row) {
      this.$modal.confirm('是否确认上架编号为"' + row.id + '"的申请？').then(() => {
        return this.updateApplicationStatus(row.id, 4) // 状态改为已上架
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('上架成功')
      }).catch(() => {})
    },
    /** 下架申请 */
    handleDeactivateApplication(row) {
      this.$modal.confirm('是否确认下架编号为"' + row.id + '"的申请？').then(() => {
        return this.updateApplicationStatus(row.id, 5) // 状态改为已下架
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('下架成功')
      }).catch(() => {})
    },
    /** 更新申请状态 */
    updateApplicationStatus(id, status) {
      return updateApplicationStatus({
        id: id,
        applicationStatus: status
      })
    }
  }
}
</script>
